package com.app.micaihu.view.main.topic.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.app.micaihu.R;
import com.app.micaihu.adapter.NewsFragmentPagerAdapter;
import com.app.micaihu.base.BaseOldFragment;
import com.app.micaihu.base.BaseListFragment;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.ConfigKeyConstant;

import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.view.main.MainActivity;
import com.app.micaihu.view.main.topic.PostSendActivity;
import com.app.utils.util.osutils.StatusBarUtils;
import com.baidu.mobstat.StatService;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 话题fragment
 * Created by linkai on 2016/9/6.
 */
public class TopicFragment extends BaseOldFragment implements ViewPager.OnPageChangeListener, View.OnClickListener {

    /********
     * 页面控件
     **********/
    private View mContextView;
    private ViewPager mViewpager;
    private MainActivity mainActivity;//特定的activity

    private String uidData;//上一次刷新数据的uid


    /***********
     * 逻辑数据
     ***********/
    private ArrayList<Fragment> fragments = new ArrayList<Fragment>();//新闻页面集合
    private TextView topicRecommd;
    private TextView topicEssence;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (UserInforManager.getInstance().isLogin()) {
            //记录当前刷新数据的uid
            uidData = UserInforManager.getInstance().getUserInfor().getUid();
        }
        if (mContextView == null) {
            mContextView = inflater.inflate(R.layout.activity_topic, null);

            StatusBarUtils.setupStatusBarViewInFragmentLinearLayout(getActivity(), mContextView, R.color.app_theme);

            mViewpager = (ViewPager) mContextView.findViewById(R.id.mViewPager);

            topicRecommd = (TextView) mContextView.findViewById(R.id.topicRecommd);
            topicEssence = (TextView) mContextView.findViewById(R.id.topicEssence);
            ImageView topicSend = (ImageView) mContextView.findViewById(R.id.topicSend);
            topicRecommd.setOnClickListener(this);
            topicEssence.setOnClickListener(this);
            topicSend.setOnClickListener(this);

            topicRecommd.setSelected(true);
            topicEssence.setSelected(false);
            initView();
        }
        return mContextView;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (UserInforManager.getInstance().isLogin()) {
//            if (fragments != null &&
//                    !TextUtils.equals(UserInforManager.getInstance().getUserInfor().getUid(), uidData)) {
//                //如果切换用户了则刷新数据
//                for (int i = 0; i < fragments.size(); i++) {
//                    if (fragments.get(i) instanceof TopicRecommendFragment) {
//                        ((TopicRecommendFragment) fragments.get(i)).flushData(true);
//                    } else {
//                        ((BaseListFragment) fragments.get(i)).flushData();
//                    }
//                }
//                //记录当前刷新数据的uid
//                uidData = UserInforManager.getInstance().getUserInfor().getUid();
//            }
//        } else {
//            if (!TextUtils.isEmpty(uidData)) {
//                for (int i = 0; i < fragments.size(); i++) {
//                    if (fragments.get(i) instanceof TopicRecommendFragment) {
//                        ((TopicRecommendFragment) fragments.get(i)).flushData(true);
//                    } else {
//                        ((BaseListFragment) fragments.get(i)).flushData();
//                    }
//                }
//                uidData = "";
//            }
//        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mainActivity = (MainActivity) activity;
    }


    /**
     * 初始化布局
     */
    private void initView() {
        TopicRecommendFragment fragmentNew = new TopicRecommendFragment();//推荐话题
        Bundle bundle = new Bundle();
        bundle.putString("indexType", "1");
        fragmentNew.setArguments(bundle);
        TopicRecommendFragment fragmentHot = new TopicRecommendFragment();//最热
        Bundle bundle1 = new Bundle();
        bundle1.putString("indexType", "2");
        fragmentHot.setArguments(bundle1);

        fragments.add(fragmentNew);
        fragments.add(fragmentHot);
        // 开始适配
        NewsFragmentPagerAdapter mAdapetr = new NewsFragmentPagerAdapter(getChildFragmentManager(), fragments);
        mViewpager.setAdapter(mAdapetr);
        mViewpager.setOnPageChangeListener(this);
        showPostnGuide(mViewpager);


    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        if (topicEssence != null && topicRecommd != null) {
            if (position == 0) {
                topicRecommd.setSelected(true);
                topicEssence.setSelected(false);
            } else if (position == 1) {
                topicRecommd.setSelected(false);
                topicEssence.setSelected(true);
            }
        }

        if (position >= 1 && fragments != null && fragments.size() >= position + 1
                && AppConfigTools.topicAttention) {
            //如果刷新状态改变 则刷新数据
            ((BaseListFragment) fragments.get(position)).flushData();
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    /**
     * 切换viewpager
     *
     * @param position
     */
    public void swithTopicFragment(int position) {
        if (fragments == null || mViewpager == null
                || position < 0 || position > fragments.size()) {
            return;
        }
        mViewpager.setCurrentItem(position);
    }


    public List<Fragment> getFragments() {
        return this.fragments;
    }

    /**
     * 更新数据
     */
//    public void updateAdapter(int zanNum, int commentNum, boolean isDelete, String attention) {
//        if (fragments != null && fragments.get(0) != null) {
//            ((TopicRecommendFragment) fragments.get(0)).updateAdapter(zanNum, commentNum, isDelete, attention);
//
//        }
//    }


    /**
     * 展示提示发帖
     *
     * @param mViewpager
     */
    private void showPostnGuide(ViewPager mViewpager) {
        if (AppConfigManager.getInstance().readConfig(ConfigKeyConstant.firstshow_post, false)
                || getActivity().isFinishing()) {
            return;
        }
        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.firstshow_post, true);

        mViewpager.postDelayed(new Runnable() {
            @Override
            public void run() {
                ArrayList<Object> parms = new ArrayList<>();
                parms.add("7");
                EventBus.getDefault().post(parms);
            }
        }, 300);


    }


    /**
     * 根据时间间隔 刷新
     */
    public void flushTopicWithTime() {
        if (fragments != null && !fragments.isEmpty()) {
            for (int i = 0; i < fragments.size(); i++) {
                if (fragments.get(i) instanceof TopicRecommendFragment) {
                    ((TopicRecommendFragment) fragments.get(i)).flushWithTime();
                }
            }
        }


    }

    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.topicRecommd:

                swithTopicFragment(0);

                break;
            case R.id.topicEssence:
                swithTopicFragment(1);
                break;
            case R.id.topicSend:
                sendPostOpration();
                break;
        }
    }


    /**
     * 发帖操作
     */
    private void sendPostOpration() {
        if (UserInforManager.getInstance().isLogin()) {
            Intent intent = new Intent(mainActivity, PostSendActivity.class);
            intent.putExtra("tansImg", UserInforManager.getInstance().getUserInfor().getTansImg());
            startActivity(intent);
            mainActivity.overridePendingTransition(R.anim.translate_slide_in_bottom, R.anim.slide_out_left);
            StatService.onEvent(getContext(), "063", "跳转发帖页面", 1);// 统计的点击
        } else {
            UserInforManager.getInstance().toLoginPage(mainActivity);
        }

    }


}
